import {useState, useEffect} from "react"

/*
@name: useKeyPress
@description: 自定义键盘事件的hooks函数
@author: ChangHao
@time: 2020-11-06 10:32:02
*/
const useKeyPress = (targetKeyCode) => {
    const [keyPressed, setKeyPressed] = useState(false);
    /*
    @name: keyDownHandler
    @description: 表示按键按下的时候让状态改变为true可以在外面被监听到。
    @author: ChangHao
    @time: 2020-11-07 15:54:32
    */
    const keyDownHandler = ({keyCode}) => {
        // console.log(keyCode, targetKeyCode)
        if (keyCode === targetKeyCode) {
            setKeyPressed(true);
            // console.log(keyPressed)
        }
    };
    /*
    @name: keyUpHandler
    @description: 当按键抬起的时候，改变为false让在外面调用改hooks的接触键盘事件。
    @author: ChangHao
    @time: 2020-11-07 15:55:43
    */
    const keyUpHandler = ({keyCode}) => {
        if (keyCode === targetKeyCode) {
            setKeyPressed(false);
            // console.log(keyPressed)
        }
    };
    //持续监听
    useEffect(() => {
        document.addEventListener('keydown', keyDownHandler);
        document.addEventListener('keyup', keyUpHandler);
        return () => {
            document.removeEventListener('keydown', keyDownHandler);
            document.removeEventListener('keyup', keyUpHandler);
        }
    })
    return keyPressed;
}


export default useKeyPress;